package com.yixun.qfbao.util;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author <a href="mailto:just_szl@hotmail.com"> Geray</a>
 * @version 1.0,2012-6-12 
 */
public class FileUploadPorxyUtil {
	private static Logger logger= LoggerFactory.getLogger(FileUploadPorxyUtil.class);

	//file1与file2在同一个文件夹下 filepath是该文件夹指定的路径	
	public static String submitPost(String url,JSONObject params,MultipartFile multipartfile){
		String fileName = multipartfile.getOriginalFilename();
		// 获取后缀名为重写文件名做准备
		String oldFileName = fileName.indexOf(".") != -1 ? fileName.substring(0,fileName.lastIndexOf(".")) : fileName;
		// String otherPath = "" + fileName;
		File saveSourceFile = new File(fileName);
		JSONObject res = new JSONObject();
		try {
			inputstreamtofile(multipartfile.getInputStream(), saveSourceFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			res.put("result","0");
			res.put("errorMsg","文件读取失败");
			return res.toJSONString();
		}
		String result=submitPost(url,params,saveSourceFile);
		if (saveSourceFile.exists() && saveSourceFile.isFile()) {
			saveSourceFile.delete();
		}
		JSONObject resultObject=JSON.parseObject(result);
		resultObject.put("fileName", oldFileName);
		return resultObject.toJSONString();
	}
	public static String submitPost(String url,JSONObject params,File _file){
		
		HttpClient httpclient = new DefaultHttpClient();
		String result = null;
		JSONObject res = new JSONObject();
		try {
	
			HttpPost httppost = new HttpPost(url);
		    FileBody file = new FileBody(_file);
		    MultipartEntity reqEntity = new MultipartEntity();
		    reqEntity.addPart("file", file);//file1为请求后台的File upload;属性   
		    if(params!=null){
		    	Iterator it = params.keySet().iterator();  
		    	while (it.hasNext()) {  
		    		String key = (String) it.next();  
		    		String value = params.getString(key);  
		    		reqEntity.addPart(key, new StringBody(value));//filename1为请求后台的普通参数;属性	
		    	}  
		    }
		    httppost.setEntity(reqEntity);
		    
		    HttpResponse response = httpclient.execute(httppost);
		    
			    
		    int statusCode = response.getStatusLine().getStatusCode();
		    
			    
			if(statusCode == HttpStatus.SC_OK){
			    	
				System.out.println("服务器正常响应.....");
				
		    	HttpEntity resEntity = response.getEntity();
		    	result = EntityUtils.toString(resEntity);
		    	EntityUtils.consume(resEntity);
		    }else{
		    	res.put("result","0");
				res.put("errorMsg","服务器错误！");
		    }
			    
			} catch (ParseException e) {
				logger.error("submitPost error: {}", e);
				res.put("result","0");
				res.put("errorMsg","文件转换错误！");
			} catch (IOException e) {
				logger.error("submitPost error: {}", e);
				res.put("result","0");
				res.put("errorMsg","文件读写错误！");
			} finally {
			    try { 
			    	httpclient.getConnectionManager().shutdown(); 
			    } catch (Exception ignore) {
			    	
			    }
			}
			result = result!=null ? result:res.toJSONString();
			return result;
		}
	
	/**
	 * 转存临时文件
	 * 
	 * @param ins
	 * @param file
	 */
	private static void inputstreamtofile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (IOException e) {
			logger.error("inputstreamtofile error: {}",e);
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileUploadPorxyUtil.submitPost("http://114.215.184.122:10016/qfb-img/api/uploadFile.api?type=1",
				null,new File("/Users/xihu/Downloads/打印乐JPG/2-找回密码－成功.jpg"));
	}
	
}
